<template>
  <!-- 已作废 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select ref="timetype" v-model="timetype" style="width: 170px; margin-right: 2px;">
          <el-option label="押金登记时间" value="createTime" />
          <el-option label="开始时间" value="beginDt" />
          <el-option label="审核时间" value="auditDt" />
          <el-option label="提瓶时间" value="takeBottleDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="收款方式:" prop="calcType">
        <el-select v-model="query.calcType" placeholder="请选择" clearable>
          <el-option v-for="(v,index) in calcTypeList" :key="index" :label="v.desc" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="1.2">
        <el-input v-model.number="query.expireDayNum" :min="0" class="text-input">
          <template slot="prepend">查看</template>
          <template slot="append">天内押金将到期的单据</template>
        </el-input>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[20205,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <el-button-group>
        <el-button v-permission="[20205,2]" type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
      </el-button-group>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data.rows"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <popups ref="popups" :calc-type-list="calcTypeList" :payment-method-list="paymentMethodList" :pay-status-list="payStatusList" :customer-type="customerType" />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
  </div>
</template>

  <script>
  import { queryExpireList, exportExpire, queryExportDomain } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import dayjs from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import Popups from './Popups'

  export default {
    name: 'already-invalid-tab',
    components: { CsmDetail, Popups },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      calcTypeList: {
        type: Array,
        required: true
      },
      paymentMethodList: {
        type: Array,
        required: true
      },
      payStatusList: {
        type: Array,
        required: true
      },
      paymenFilList: {
        type: Array,
        required: true
      },
      customerType: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        timetype: 'createTime',
        date: [],
        exportDomain: {},
        query: {
          calcType: 3,
          expireDayNum: 30
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              fixed: 'left'
            },
            {
              prop: 'depositCode',
              label: '押金单号',
              fixed: 'left',
              width: 110,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.showDeposit(row)}>{row.depositCode}</el-link>
            },
            {
              prop: 'takeBottleDt',
              label: '提瓶时间',
              width: 160,
              render: (h, { row }) => <span>{ row.takeBottleDt && parseTime(row.takeBottleDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'calcType',
              label: '收款方式',
              render: (h, { row }) => <span>{ row.calcType && formatColumnMap(this.calcTypeList, 'value', row.calcType, 'desc') }</span>
            },
            {
              prop: 'createTime',
              label: '押金登记时间',
              width: 160,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'auditDt',
              label: '审核时间',
              width: 160,
              render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'beginDt',
              label: '开始时间',
              width: 120,
              render: (h, { row }) => <span>{ row.beginDt && parseTime(row.beginDt, '{y}-{m}-{d}') }</span>
            },
            {
              prop: 'totalCount',
              label: '总数量',
              width: 80
            },
            {
              prop: 'goodsDesc',
              label: '商品描述',
              width: 180
            },
            {
              prop: 'totalDeposit',
              align: 'right',
              label: '总押金',
              width: 80
            },
            {
              prop: 'fee1',
              align: 'right',
              label: '手续费',
              width: 80,
              render: (h, { row }) => <span>{ row.fee1 || <span>0.00</span> }</span>
            },
            {
              prop: 'ckOrgName',
              label: '押瓶机构',
              width: 120
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              width: 110,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
            },
            {
              prop: 'csmName',
              label: '客户名称',
              width: 100
            },
            {
              prop: 'csmPhone',
              label: '联系电话',
              width: 120
            },
            {
              prop: 'expirationDt',
              label: '到期时间',
              width: 120,
              render: (h, { row }) => <span>{ row.expirationDt && parseTime(row.expirationDt, '{y}-{m}-{d}') }</span>
            },
            {
              prop: 'expirationDay',
              label: '有效期',
              render: (h, { row }) => <span>{ this.dateDiff(row.expirationDt) }</span>
            }
          ],
          data: {
            rows: []
          }
        }
      }
    },
    computed: {},
    async created() {
      await this.getExportDomain()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 列表
      async fetchData({ currentPage, pageSize }) {
        const params = { ...this.query }
        if (this.date && this.date.length === 2) {
          params[this.timetype] = dayjs(this.date[0]).format('YYYY-MM-DD') + ' 00:00:00'
          params[`${this.timetype}End`] = dayjs(this.date[1]).format('YYYY-MM-DD') + ' 23:59:59'
        }
        const query = {
          ...this._getQuery(params),
          currentPage,
          pageSize
        }
        const result = await queryExpireList(query)
        this.tableData.data.rows = result.data.rows
        if (currentPage === 1) {
          this.tableData.total = result.data.total
        }
      },
      dateDiff(expirationDt) {
        if (expirationDt) {
          var startTime = new Date(Date.parse(new Date())).getTime()
          var endTime = new Date(Date.parse(expirationDt)).getTime()
          // 计算毫秒数的差，并换算成天数；
          var diff = Math.abs(startTime - endTime)
          var days = parseInt(diff / (1000 * 60 * 60 * 24), 10)
          return endTime >= startTime ? days : '-' + days
        } else {
          return ''
        }
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查询
      async search() {
        if (!this.query.expireDayNum) {
          this.$message.warning('请输入天数')
          return
        }
        if (this.query.expireDayNum > 90) {
          this.$message.warning('查询范围仅限90天之内')
          return
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 押金明细
      showDeposit(row) {
        console.log('押金明细', row)
        this.$refs.popups.open(row, 'info')
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          const params = { ...this.query }
          if (this.date && this.date.length === 2) {
            params[this.timetype] = dayjs(this.date[0]).format('YYYY-MM-DD') + ' 00:00:00'
            params[`${this.timetype}End`] = dayjs(this.date[1]).format('YYYY-MM-DD') + ' 23:59:59'
          }
          exportExpire({
            paramInfo: params,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
  </script>

  <style lang="scss" scoped>
    /deep/.el-input .el-input-group__append:last-child {
      border: 1px solid #DCDFE6;
    }
    .text-input /deep/ .el-input__inner {
      width: 50px;
    }
  </style>

